<?php



namespace App\Http\Controllers\Backend1;

use App\Zesow\Aliyun\Vod;
use App\Services\Business\Models\VideoTag;
use Illuminate\Http\Request;
use App\Events\VideoUploadTokenEvent;
use Illuminate\Support\Facades\DB;
use App\Services\Business\Models\MediaVideo;

class MediaVideoController extends BaseController
{
    public function index(Request $request)
    {
        $keywords = $request->input('keywords');
        $isOpen = (int)$request->input('is_open');
        $categoryId = (int)$request->input('categoryId');
        $myCategoryId = (int)$request->input('myCategoryId');

        $videos = MediaVideo::query()
            ->select([
                'id', 'title', 'thumb', 'duration', 'size', 'storage_driver', 'storage_file_id',
                'transcode_status', 'ref_count', 'created_at', 'updated_at','category_id','cate_id',
                'my_category_id'
            ])
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when(in_array($isOpen, [0, 1]), function ($query) use ($isOpen) {
                $query->where('is_open', $isOpen);
            })
            ->when($categoryId,function ($query) use($categoryId){
                $query->where('category_id','=',$categoryId);
            })
            ->when($myCategoryId,function ($query) use($myCategoryId){
                $query->where('my_category_id','=',$myCategoryId);
            })
            ->orderByDesc('id')
            ->paginate($request->input('size', 10));

        return $this->successData($videos);
    }
    //公开课
    public function  openVideos()
    {

        $videos =  MediaVideo::query()
            ->with(['user'])
            ->where('is_open',1)
            ->orderByDesc('created_at')
            ->get()
            ->toArray();
        return  $this->successData(compact('videos'));

    }
    public function store(Request $request)
    {
        $title = mb_substr(strip_tags($request->input('title', '')), 0, 255);
        $thumb = $request->input('thumb', '');
        $duration = (int)$request->input('duration');
        $size = (int)$request->input('size');
        $storageDriver = $request->input('storage_driver');
        $storageFileId = $request->input('storage_file_id');
        $isOpen = (int)$request->input('is_open');
        $categoryId = (int)$request->input('category_id');
        $myCategoryId = (int)$request->input('my_category_id');
        $cateId = (string)$request->input('cate_id');
        $tags = (array)$request->input('tags');
        $tagCategoryId = (int)$request->input('tag_category_id');

        $mediaVideo = MediaVideo::create([
            'title' => $title,
            'thumb' => $thumb,
            'duration' => $duration,
            'size' => $size,
            'storage_driver' => $storageDriver,
            'storage_file_id' => $storageFileId,
            'is_open' => $isOpen,
            'category_id'=>$categoryId,
            'my_category_id'=>$myCategoryId,
            'cate_id'=>$cateId
        ]);

        event(new VideoUploadTokenEvent($storageFileId, $storageDriver, 'media_video', $mediaVideo['id']));
        if(!empty($tags)){
           foreach ($tags as $tag){
               VideoTag::create([
                   "video_id"=>$mediaVideo->id,
                   "video_tags_id"=>$tag,
                   "tag_category_id"=>$tagCategoryId
               ]);
           }
        }
        return $this->successData($mediaVideo);
    }

    public function deleteVideos(Request $request, Vod $aliyunVod, \App\Zesow\Tencent\Vod $tencentVod)
    {
        $ids = $request->input('ids');
        if (!$ids || !is_array($ids)) {
            return $this->error(__('请选择需要删除的视频'));
        }

        $videos = MediaVideo::query()->whereIn('id', $ids)->select(['id', 'storage_driver', 'storage_file_id'])->get();
        if (!$videos) {
            return $this->error(__('数据为空'));
        }
        $aliyunFileIds = [];
        $tencentFileIds = [];
        foreach ($videos as $videoItem) {
            if ($videoItem['storage_driver'] === 'aliyun') {
                $aliyunFileIds[] = $videoItem['storage_file_id'];
            } elseif ($videoItem['storage_driver'] === 'tencent') {
                $tencentFileIds[] = $videoItem['storage_file_id'];
            }
        }

        DB::transaction(function () use ($ids, $aliyunFileIds, $tencentFileIds, $aliyunVod, $tencentVod) {
            // 删除本地记录
            MediaVideo::query()->whereIn('id', $ids)->delete();
            if ($aliyunFileIds) {
                $aliyunVod->deleteVideos($aliyunFileIds);
            }
            if ($tencentFileIds) {
                $tencentVod->deleteVideos($tencentFileIds);
            }
        });

        return $this->successData();
    }
}
